import { NextRequest, NextResponse } from 'next/server';
import { GloableResponseItem, ResponseEnum } from '@/utils/request/res';
import { Auth, type ExtendedNextApiRequest, ResponseHandler, LogOperation } from '@/utils/decorator';
import prisma from '@/utils/db/PrismaService';
import { BaseController } from '@/utils/request/BaseController';
import { GET as HttpGet, POST as HttpPost, PUT as HttpPut, DELETE as HttpDelete } from '@/utils/decorator';
import { createAllMethodHandlers } from '@/utils/request/routeRegistry';
import { Prisma } from '@prisma/client';
import { getCurrentTimeInShanghai } from '@/utils/storage';
import { TimerTaskManager } from '@/utils/timer/TimerTaskManager';
// API中不再负责初始化，只使用已初始化的管理器

class SystemTimerController extends BaseController {
    
    // 获取定时任务列表
    @Auth()
    @ResponseHandler()
    @HttpGet()
    static async getTimerTaskList(request: ExtendedNextApiRequest) {
        const params: any = request.customBody;
        const page = parseInt(params.page || '1');
        const pageSize = parseInt(params.pageSize || '10');
        const offset = (page - 1) * pageSize;

        // 构建查询条件
        let whereConditions = Prisma.sql`WHERE del_flag = 1`;

        if (params.taskName) {
            whereConditions = Prisma.sql`${whereConditions} AND task_name LIKE ${`%${params.taskName}%`}`;
        }

        if (params.taskType) {
            whereConditions = Prisma.sql`${whereConditions} AND task_type = ${params.taskType}`;
        }

        if (params.status !== undefined && params.status !== '') {
            whereConditions = Prisma.sql`${whereConditions} AND status = ${parseInt(params.status)}`;
        }

        try {
            // 获取总数
            const countResult = await prisma.$queryRaw<{ count: BigInt }[]>(Prisma.sql`
                SELECT COUNT(*) as count
                FROM sys_timer_task
                ${whereConditions}
            `);
            const total = Number(countResult[0]?.count || 0);

            // 获取列表数据
            const list = await prisma.$queryRaw<any[]>(Prisma.sql`
                SELECT 
                    id, task_name, task_code, cron_expression, task_type, 
                    description, status, create_time, update_time, 
                    last_run_time, next_run_time, run_count,task_config
                FROM sys_timer_task
                ${whereConditions}
                ORDER BY create_time DESC
                LIMIT ${pageSize} OFFSET ${offset}
            `);

            // 获取正在执行的任务ID列表
            const executingTaskIds = TimerTaskManager.getInstance().getExecutingTaskIds();
            
            return GloableResponseItem(ResponseEnum.success, "", {
                list: list.map(item => ({
                    ...item,
                    id: Number(item.id),
                    isExecuting: executingTaskIds.includes(Number(item.id)) // 添加执行状态
                })),
                pagination: {
                    current: page,
                    pageSize,
                    total
                }
            });
        } catch (error) {
            console.error('获取定时任务列表失败:', error);
            return GloableResponseItem(ResponseEnum.fail, "获取列表失败", null);
        }
    }

    // 新增定时任务
    @Auth()
    @ResponseHandler()
    @HttpPost()
    @LogOperation({
        module: "定时任务管理",
        operationName: "新增定时任务"
    })
    static async addTimerTask(request: ExtendedNextApiRequest) {
        const data = request.customBody;
        const currentTime = getCurrentTimeInShanghai();
        const userId = parseInt(request.user?.id || '0');
        try {
            // 验证cron表达式
            if (!TimerTaskManager.validateCronExpression(data.cron_expression)) {
                return GloableResponseItem(ResponseEnum.fail, "Cron表达式格式不正确", null);
            }

            // 检查任务编码是否重复
            const existingTask = await prisma.sysTimerTask.findUnique({
                where: { task_code: data.task_code }
            });

            if (existingTask) {
                return GloableResponseItem(ResponseEnum.fail, "任务编码已存在", null);
            }

            // 计算下次执行时间
            const nextRunTime = TimerTaskManager.getNextRunTime(data.cron_expression);


            const newTask = await prisma.sysTimerTask.create({
                data: {
                    task_name: data.task_name,
                    task_code: data.task_code,
                    cron_expression: data.cron_expression,
                    task_type: data.task_type,
                    task_config: data.task_config ? JSON.stringify(data.task_config) : "{}",
                    description: data.description || null,
                    status: data.status || 0,
                    create_user_id: userId,
                    create_time: currentTime,
                    update_time: currentTime,
                    next_run_time: nextRunTime
                }
            });

            // 如果任务状态为启用，则启动定时任务
            if (newTask.status === 1) {
                TimerTaskManager.getInstance().startTask(newTask);
            }

            return GloableResponseItem(ResponseEnum.success, "新增成功", { id: newTask.id });
        } catch (error) {
            console.error('新增定时任务失败:', error);
            return GloableResponseItem(ResponseEnum.fail, "新增失败", null);
        }
    }

    // 更新定时任务
    @Auth()
    @ResponseHandler()
    @HttpPut()
    @LogOperation({
        module: "定时任务管理",
        operationName: "更新定时任务"
    })
    static async updateTimerTask(request: ExtendedNextApiRequest) {
        const data = request.customBody;
        const currentTime = getCurrentTimeInShanghai();

        try {
            const taskId = parseInt(data.id);

            // 检查任务是否正在执行
            const taskManager = TimerTaskManager.getInstance();
            if (taskManager.isTaskExecuting(taskId)) {
                return GloableResponseItem(ResponseEnum.fail, "任务正在执行中，请等待执行完成后再进行更新操作", null);
            }

            // 验证cron表达式
            if (data.cron_expression && !TimerTaskManager.validateCronExpression(data.cron_expression)) {
                return GloableResponseItem(ResponseEnum.fail, "Cron表达式格式不正确", null);
            }

            // 获取原任务信息
            const originalTask = await prisma.sysTimerTask.findUnique({
                where: { id: taskId }
            });

            if (!originalTask) {
                return GloableResponseItem(ResponseEnum.fail, "任务不存在", null);
            }

            // 如果修改了任务编码，检查是否重复
            if (data.task_code && data.task_code !== originalTask.task_code) {
                const existingTask = await prisma.sysTimerTask.findUnique({
                    where: { task_code: data.task_code }
                });

                if (existingTask) {
                    return GloableResponseItem(ResponseEnum.fail, "任务编码已存在", null);
                }
            }

            // 构建更新数据
            const updateData: any = {
                update_time: currentTime
            };

            if (data.task_name) updateData.task_name = data.task_name;
            if (data.task_code) updateData.task_code = data.task_code;
            if (data.cron_expression) {
                updateData.cron_expression = data.cron_expression;
                updateData.next_run_time = TimerTaskManager.getNextRunTime(data.cron_expression);
            }
            if (data.task_type) updateData.task_type = data.task_type;
            if (data.task_config !== undefined) updateData.task_config = data.task_config ? JSON.stringify(data.task_config) : null;
            if (data.description !== undefined) updateData.description = data.description;
            if (data.status !== undefined) updateData.status = data.status;

            const updatedTask = await prisma.sysTimerTask.update({
                where: { id: taskId },
                data: updateData
            });

            // 更新定时任务调度
            const manager = TimerTaskManager.getInstance();
            manager.stopTask(taskId);
            if (updatedTask.status === 1) {
                manager.startTask(updatedTask);
            }
            return GloableResponseItem(ResponseEnum.success, "更新成功", null);
        } catch (error) {
            console.error('更新定时任务失败:', error);
            return GloableResponseItem(ResponseEnum.fail, "更新失败", null);
        }
    }

    // 删除定时任务
    @Auth()
    @ResponseHandler()
    @HttpDelete()
    @LogOperation({
        module: "定时任务管理",
        operationName: "删除定时任务"
    })
    static async deleteTimerTask(request: ExtendedNextApiRequest) {
        const data = request.customBody;
        const currentTime = getCurrentTimeInShanghai();

        try {
            const taskId = parseInt(data.id);

            // 检查任务是否正在执行
            const timerManager = TimerTaskManager.getInstance();
            if (timerManager.isTaskExecuting(taskId)) {
                return GloableResponseItem(ResponseEnum.fail, "任务正在执行中，请等待执行完成后再进行删除操作", null);
            }

            // 停止定时任务
            timerManager.stopTask(taskId);

            await prisma.sysTimerTask.delete({
                where: { id: taskId },
            })
            return GloableResponseItem(ResponseEnum.success, "删除成功", null);
        } catch (error) {
            console.error('删除定时任务失败:', error);
            return GloableResponseItem(ResponseEnum.fail, "删除失败", null);
        }
    }

    // 启动/停止定时任务
    @Auth()
    @ResponseHandler()
    @HttpPost()
    @LogOperation({
        module: "定时任务管理",
        operationName: "启停定时任务"
    })
    static async toggleTimerTask(request: ExtendedNextApiRequest) {
        const data = request.customBody;
        const currentTime = getCurrentTimeInShanghai();

        try {
            const taskId = parseInt(data.id);
            const status = parseInt(data.status); // 1启用 0停用

            const task = await prisma.sysTimerTask.findUnique({
                where: { id: taskId }
            });

            if (!task) {
                return GloableResponseItem(ResponseEnum.fail, "任务不存在", null);
            }

            // 更新状态
            const updatedTask = await prisma.sysTimerTask.update({
                where: { id: taskId },
                data: {
                    status,
                    update_time: currentTime,
                    next_run_time: status === 1 ? TimerTaskManager.getNextRunTime(task.cron_expression) : null
                }
            });

            // 启停定时任务
            const manager = TimerTaskManager.getInstance();
            if (status === 1) {
                manager.startTask(updatedTask);
            } else {
                manager.stopTask(taskId);
            }

            return GloableResponseItem(ResponseEnum.success, status === 1 ? "启动成功" : "停用成功", null);
        } catch (error) {
            console.error('启停定时任务失败:', error);
            return GloableResponseItem(ResponseEnum.fail, "操作失败", null);
        }
    }

    // 手动执行定时任务
    @Auth()
    @ResponseHandler()
    @HttpPost()
    @LogOperation({
        module: "定时任务管理",
        operationName: "手动执行任务"
    })
    static async executeTimerTask(request: ExtendedNextApiRequest) {
        const data = request.customBody;

        try {
            const taskId = parseInt(data.id);

            const task = await prisma.sysTimerTask.findUnique({
                where: { id: taskId }
            });

            if (!task) {
                return GloableResponseItem(ResponseEnum.fail, "任务不存在", null);
            }

            // 手动执行任务
            const result = await TimerTaskManager.getInstance().executeTask(task);

            return GloableResponseItem(ResponseEnum.success, "执行完成", { result });
        } catch (error) {
            console.error('手动执行任务失败:', error);
            return GloableResponseItem(ResponseEnum.fail, "执行失败", null);
        }
    }

    // 获取任务执行日志
    @Auth()
    @ResponseHandler()
    @HttpGet()
    static async getTimerTaskLogs(request: ExtendedNextApiRequest) {
        const params: any = request.customBody;
        const page = parseInt(params.page || '1');
        const pageSize = parseInt(params.pageSize || '10');
        const offset = (page - 1) * pageSize;
        const taskId = parseInt(params.taskId);

        try {
            // 获取总数
            const countResult = await prisma.$queryRaw<{ count: BigInt }[]>(Prisma.sql`
                SELECT COUNT(*) as count
                FROM sys_timer_log
                WHERE task_id = ${taskId}
            `);
            const total = Number(countResult[0]?.count || 0);

            // 获取日志列表
            const logs = await prisma.$queryRaw<any[]>(Prisma.sql`
                SELECT 
                    id, task_id, execute_time, status, result, error_msg, cost_time
                FROM sys_timer_log
                WHERE task_id = ${taskId}
                ORDER BY execute_time DESC
                LIMIT ${pageSize} OFFSET ${offset}
            `);

            return GloableResponseItem(ResponseEnum.success, "", {
                list: logs.map(item => ({
                    ...item,
                    id: Number(item.id),
                    task_id: Number(item.task_id)
                })),
                pagination: {
                    current: page,
                    pageSize,
                    total
                }
            });
        } catch (error) {
            console.error('获取任务执行日志失败:', error);
            return GloableResponseItem(ResponseEnum.fail, "获取日志失败", null);
        }
    }

    // 获取任务类型选项
    @Auth()
    @ResponseHandler()
    @HttpGet()
    static async getTaskTypes(request: ExtendedNextApiRequest) {
        const taskTypes = [
            { value: 'api_call', label: 'API调用' },
            { value: 'database_cleanup', label: '数据库清理' },
            { value: 'data_sync', label: '数据同步' },
            { value: 'report_generate', label: '报表生成' },
            { value: 'system_monitor', label: '系统监控' },
            { value: 'custom', label: 'Shell脚本' },
            { value: 'javascript', label: 'JavaScript代码' }
        ];

        return GloableResponseItem(ResponseEnum.success, "", taskTypes);
    }

    // 获取任务统计信息
    @Auth()
    @ResponseHandler()
    @HttpGet()
    static async getTimerTaskStats(request: ExtendedNextApiRequest) {
        try {
            // 获取任务总数
            const totalCount = await prisma.sysTimerTask.count({
                where: { del_flag: 1 }
            });

            // 获取启用任务数
            const activeCount = await prisma.sysTimerTask.count({
                where: { del_flag: 1, status: 1 }
            });

            // 获取今日执行次数
            const today = getCurrentTimeInShanghai().split(' ')[0];
            const todayExecuteCount = await prisma.sysTimerLog.count({
                where: {
                    execute_time: {
                        startsWith: today
                    }
                }
            });

            // 获取今日成功执行次数
            const todaySuccessCount = await prisma.sysTimerLog.count({
                where: {
                    execute_time: {
                        startsWith: today
                    },
                    status: 1
                }
            });

            return GloableResponseItem(ResponseEnum.success, "", {
                totalCount,
                activeCount,
                inactiveCount: totalCount - activeCount,
                todayExecuteCount,
                todaySuccessCount,
                todayFailCount: todayExecuteCount - todaySuccessCount
            });
        } catch (error) {
            console.error('获取任务统计失败:', error);
            return GloableResponseItem(ResponseEnum.fail, "获取统计失败", null);
        }
    }
}

// 导出所有HTTP方法的处理函数
export const { GET, POST, PUT, DELETE } = createAllMethodHandlers(SystemTimerController);